﻿using Microsoft.AspNetCore.Mvc.Filters;  //过滤器的命名空间
using Microsoft.Extensions.Logging;      //ILogger日志记录器的命名空间
using System;

namespace XfTechOAWeb.Infrastructure.Filters
{
    /// <summary>
    /// 全局异常过滤器--发生异常时在日志文件中输出错误信息
    /// </summary>
    public class GlobalExceptionFilter : IExceptionFilter
    {
        /// <summary>
        /// 注入nlog
        /// </summary>
        private readonly ILogger<GlobalExceptionFilter> _logger;

        public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
        {
            _logger = logger;
        }
        /// <summary>
        /// 异常处理
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            string con = context.RouteData.Values["controller"].ToString();
            string action = context.RouteData.Values["action"].ToString();
            string api = context.HttpContext.Request.Path;
            Exception ex = new Exception();

            string messing = $"用户访问了:{api},错误信息为:{ex.Message}";
            _logger.LogError(messing);
            context.ExceptionHandled = true;
        }
    }
}
